//
//  PersonalAddressBook.swift
//  ProjectDemo
//
//  Created by caoxiaozhu on 2018/8/15.
//  Copyright © 2018年 caoxiaozhu. All rights reserved.
//

import UIKit

class PersonalAddressBook: UIViewController,UITableViewDataSource,UITableViewDelegate {
    
    let mainTableView : UITableView = UITableView()
    var modelArr : Array = [PersonModel]()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadData { (model) in
            self.modelArr += model
            self.mainTableView.reloadData()
        }

        setupUI()
    }
}

extension PersonalAddressBook{
    
    func setupUI(){
        
        view.backgroundColor = UIColor.white
        
        let rightButton = UIButton(type: .contactAdd)
        rightButton.addTarget(self, action: #selector(rightClick), for: .touchUpInside)
        let rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        self.navigationItem.rightBarButtonItem = rightBarButtonItem
        
        mainTableView.frame = view.frame
        mainTableView.dataSource = self
        mainTableView.delegate = self
        view.addSubview(mainTableView)
    
    }
    
    func rightClick(){
        print("点击了按钮")
    }
}

extension PersonalAddressBook{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return modelArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellID")
        
        if cell == nil {
            cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cellID")
        }
        
        cell?.textLabel?.text = modelArr[indexPath.row].name
        cell?.detailTextLabel?.text = modelArr[indexPath.row].tele
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let personDetails = PersonalAddressBookDetails()
        personDetails.model = modelArr[indexPath.row]
        navigationController?.pushViewController(personDetails, animated: true)
    }
}

extension PersonalAddressBook{
    
    func loadData(completion : @escaping ([PersonModel]) ->()){
        
        DispatchQueue.global().async {
            
            var tempArr = [PersonModel]()
            
            for i in 0..<20 {
                let person = PersonModel()
                person.name = "zhangsan ----\(i)"
                person.title = "boss"
                person.tele = "1860" + String(format: "%06d", arc4random_uniform(100000))
                tempArr.append(person)
            }
            
            DispatchQueue.main.async {
                completion(tempArr)
            }
        }
    }
}
